//
//  MyAccountViewController.m
//  Civacrm
//
//  Created by zhk on 2017/2/7.
//  Copyright © 2017年 王桂敏. All rights reserved.
//

#import "MyAccountViewController.h"
#import "OrganizationViewController.h"

static NSString * MyAccountTableViewCellReuseID = @"AccountTableView";
static NSString * MyORGTableViewCellReuseID = @"ORG";

@interface MyAccountViewController ()<UITableViewDelegate,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic , strong) UITableView * accountTableView;

@property (nonatomic , strong) NSMutableArray * dataArray;

@property (nonatomic , strong) UIImageView * userImageView;

@property (nonatomic , strong) UILabel * genderLabel;

@property (nonatomic , strong) UIImagePickerController * imagePicker;

@property (nonatomic , strong) UIImage * tempImage;

@property (nonatomic , strong) UIButton *selectButton;

@property (nonatomic , strong) UIView *sectionView;

@end

@implementation MyAccountViewController


// 用于控制section 1的开关 点击事件改变btn的selected状态 根据btn的selected去reload section 1 的 row
- (UIButton *)selectButton{
    if (!_selectButton) {
        self.selectButton = [UIButton buttonOfImageForNormalWithImage:@"icon_showall" frame:CGRectMake(kScreenWidth - 50, 10, 50, 50) target:self action:@selector(handleSelectButton:)];
        [_selectButton setImage:Image(@"icon_hidden") forState:UIControlStateSelected];
        
    }
    return _selectButton;
}

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray arrayWithObjects:@"头像",@"用户名",@"手机号",@"性别",@"所在地区", nil];
    }
    return _dataArray;
}

-(UIImageView *)userImageView
{
    if (!_userImageView) {
        _userImageView = [[UIImageView alloc]init];
        _userImageView.layer.masksToBounds = YES;
        _userImageView.layer.cornerRadius = 30;
        _userImageView.contentMode = UIViewContentModeScaleAspectFill;

    }
    return _userImageView;
}

- (UILabel *)genderLabel
{
    if (!_genderLabel) {
        _genderLabel = [[UILabel alloc]init];
        _genderLabel.font = font(28);
        _genderLabel.textColor = ColorWithHexString(@"a0c0d2");
    }
    return _genderLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigation];
    [self initView];
}

- (void)initView
{
    self.accountTableView = [[UITableView alloc]initWithFrame:self.view.frame style:(UITableViewStyleGrouped)];
    self.accountTableView.delegate = self;
    self.accountTableView.dataSource = self;
    [self.view addSubview:self.accountTableView];
    [self.accountTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:MyAccountTableViewCellReuseID];
    [self.accountTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:MyORGTableViewCellReuseID];
    self.accountTableView.backgroundColor = GlobalBgColor;
    self.accountTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.sectionView = [UIView viewWithFrame:CGRectMake(0, 0, kScreenWidth, 60) bgColor:ClearColor];
    UILabel *sectionLabel = [UILabel labelWithTitle:@"    我的机构" frame:CGRectMake(0, 10, kScreenWidth, 50) font:font(32) textColor:ColorWithHexString(@"4e778f") bgColor:WhiteColor];
    [self.sectionView addSubview:sectionLabel];
    [self.sectionView addSubview:self.selectButton];
}


- (void)changeGender
{
    [self showIndeterminate];
    
    [self.manager postWithURL:NET_EditGender param:self.params delegate:self isEncrypt:NO type:NetWorkingType1];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    NSData * data = UIImageJPEGRepresentation(info[UIImagePickerControllerOriginalImage], 0.1);
    NSString * imageString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    self.params[@"headImg"] = imageString;
    [self dismissViewControllerAnimated:YES completion:nil];
    self.tempImage = [[UIImage alloc]init];
    self.tempImage =  info[UIImagePickerControllerOriginalImage];
    [self postInfomation];
}

- (void)postInfomation{
    
    [self showIndeterminate];
    [self.manager postWithURL:NET_ChangeUserImage param:self.params delegate:self isEncrypt:NO type:NetWorkingType0];
    
}

- (void)networkingHandleSuccess:(NetworkingHandle *)handle parameters:(NSDictionary *)parameters responseObject:(id)responseObject type:(NetWorkingType)type
{
    [self hideHud];
    if (type == NetWorkingType0) {
//        修改头像
        self.userImageView.image = self.tempImage;
        if ([responseObject isKindOfClass:[NSString class]]) {
            self.iconURL = responseObject;
        }

        
    }else if(type == NetWorkingType1){
//        修改性别
        self.gender = self.params[@"sex"];

        self.genderLabel.text = [self.gender integerValue] ? @"男" : @"女";
    }
}

- (void)networkingHandleWarning:(NetworkingHandle *)handle responseObject:(id)responseObject type:(NetWorkingType)type
{
    [self hideHud];
}

- (void)networkingHandlefail:(NetworkingHandle *)handle type:(NetWorkingType)type
{
    [self hideHud];
    [self showErrorWithStatus:@"网络请求失败，请重试"];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - buttonAction
- (void)handleSelectButton:(UIButton *)sender{
    sender.selected = !sender.selected;
    [self.accountTableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
    
}
#pragma mark - tableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        
        OrganizationViewController * orgVC = [[OrganizationViewController alloc]init];
        [self.navigationController pushViewController:orgVC animated:YES];
        
    }
        else if (indexPath.section == 0 && indexPath.row == 0){
    
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.allowsEditing = NO;
            UIAlertAction * lib = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
            }];
            UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
            }];
            UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    
            }];
    
            [alert addAction:lib];
            [alert addAction:camera];
            [alert addAction:cancel];
            [self presentViewController:alert animated:YES completion:^{}];
    
        }
    else if (indexPath.section == 0 && indexPath.row == 3){
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
        UIAlertAction * man = [UIAlertAction actionWithTitle:@"男" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.params[@"sex"] = @"1";
            [self changeGender];
        }];
        UIAlertAction * women = [UIAlertAction actionWithTitle:@"女" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.params[@"sex"] = @"0";
            [self changeGender];
        }];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:man];
        [alert addAction:women];
        [alert addAction:cancel];
        
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 80;
        }else if (indexPath.row == 4){
            return h(138);
        }
        else
        {
            return 50;
        }
    }
    
    
    else
    {
        return 50;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        
        return self.sectionView;
    } else {
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.1f;
    } else {
        return 60;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.dataArray.count;
    }else
    {
        if (!self.selectButton.isSelected) {
            return 0;
        } else {
            return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MyAccountTableViewCellReuseID forIndexPath:indexPath];
        cell.textLabel.font = font(32);
        cell.textLabel.textColor = ColorWithHexString(@"4e778f");
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = self.dataArray[indexPath.row];
        switch (indexPath.row) {
            case 0:
            {
                [cell.contentView addSubview:self.userImageView];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                [_userImageView sd_setImageWithURL:[NSURL URLWithString:self.iconURL] placeholderImage:Image(@"daititouxiang")];
                [_userImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.offset(-15);
                    make.centerY.equalTo(cell.contentView);
                    make.size.mas_offset(CGSizeMake(60, 60));
                }];
            }
                break;
            case 1:
            {
                UILabel * nameLabel = [[UILabel alloc]init];
                [cell.contentView addSubview:nameLabel];
                nameLabel.font = font(28);
                nameLabel.textColor = ColorWithHexString(@"a0c0d2");
                nameLabel.text = self.nickName;
                [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.offset(-10);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
                break;
            case 2:
            {
                UILabel * phoneLabel = [[UILabel alloc]init];
                [cell.contentView addSubview:phoneLabel];
                phoneLabel.font = font(28);
                phoneLabel.textColor = ColorWithHexString(@"a0c0d2");
                phoneLabel.text = self.phone;
                [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.offset(-10);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
                break;
            case 3:
            {
                
                [cell.contentView addSubview:self.genderLabel];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                self.genderLabel.text = [self.gender integerValue] ? @"男" : @"女";
                [self.genderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.offset(-10);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
                break;
            case 4:
            {
                UILabel * provinceLabel = [[UILabel alloc]init];
                [cell.contentView addSubview:provinceLabel];
                provinceLabel.font = font(28);
                provinceLabel.textColor = ColorWithHexString(@"a0c0d2");
                provinceLabel.text = self.province;
                provinceLabel.numberOfLines = 0;
                provinceLabel.textAlignment = NSTextAlignmentRight;
                [provinceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.offset(-10);
                    make.top.equalTo(cell.contentView);
                    make.size.mas_offset(CGSizeMake(w(365), h(138)));
                }];
            }
                break;
            default:
                break;
        }
        return cell;
    }else
    {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MyORGTableViewCellReuseID forIndexPath:indexPath];
        cell.textLabel.font = font(32);
        cell.textLabel.textColor = ColorWithHexString(@"4e778f");
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UILabel * tempLabel = [[UILabel alloc]init];
            [cell.contentView addSubview:tempLabel];
            [tempLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(20);
                make.centerY.equalTo(cell.contentView);
            }];
            tempLabel.textColor = ColorWithHexString(@"4e778f");
            tempLabel.text = self.orgName;
            tempLabel.font = font(28);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}

- (void)initNavigation
{
    self.title = @"我的账号";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
